# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import datetime
import os
import random
from multiprocessing.dummy import Pool

from core import Account, User
from setting import *


"""
Author:lu
E-mail:luliangce@gmail.com
Created:2018/4/1
Update:
脚本实现注册机器人,因为IP封锁暂时未测试
"""


class SignUpMachine(object):

    def __init__(self, count=1):
        """初始化

        Keyword Arguments:
            count {int} -- 要注册数量 (default: {10})
        """

        self.names = self.__NamesFactory(count)  # 初始化需要注册数量的名字
        self.password = PASSWORD
        self.count = count
        self.mail = MAIL

    def __NamesFactory(self):
        """随机选取姓名

        Returns:
            [list] -- 从setting中设置的NAMES文件(默认firstname.txt)
                      中随机选取指定数量的人名
        """

        count = self.count
        # 选择需要注册的名字
        with open(NAMES, "r") as f:
            namelist = f.read().split("\n")
        if count < len(namelist):
            names = random.sample(namelist, count)
        else:
            names = [random.choice(namelist) for i in xrange(count)]
        return names

    def __main_process(self, firstname):
        """注册账号的函数,用于多线程调用
        根据firstname,由ins生成username,密码使用setting中PASSWORD列表中的随机一个.
        email为setting中设置的列表中任意一个函数传入username生成,保证唯一性
        """
        try:
            SignUp = Account()
            # 在随机选择的人名后加上随机6位数字,如此出现重复的可能将会很小.
            username = firstname+str(random.randint(100000, 999999))
            password = random.choice(PASSWORD)
            email = random.choice(MAIL)(username)
            r = SignUp.signUp(username=username, password=password,
                              email=email, firstname=firstname)
            if r:
                line = "{} {} {} {} {}\n".format(
                    username, password, firstname, SignUp.user_id, datetime.datetime.now())
                with file(ACCOUNTS, "a") as target:
                    target.write(line)

                logger.info("{} 注册成功,已经写入文件{}".format(firstname, ACCOUNTS))
                return
            logger.info("{} 注册失败".format(firstname))
        except Exception as e:
            logger.info("{} 注册失败".format(firstname))
            logger.debug("{}".format(e))

    def run(self):
        logger.info("开始初始化注册机器人,需要注册{}个".format(self.count))
        pool = Pool(self.count)
        pool.map(self.__main_process, self.names)
        logger.info("全部操作完成")


def main():
    obj = SignUpMachine(1)
    obj.run()


if __name__ == '__main__':
    main()
